<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/1/9
 * Time: 下午3:39
 */

namespace Biz\model\trade;

use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\GoodsSku as mGoodsSku;
use Medoo\Medoo;


class Cart extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_trade';

    const _DATABASE_ = 'shop_trade';

    const _TABLE_NAME = 'cart';


    //状态
    const STATUS_ACTIVE = 0;//购物车可用状态
    const STATUS_DELETE = 2;//删除状态
    const STATUS_FAIL = 3;//失效商品标记


    //数量判断
    const ITEM_TOTAL_SUM = 120;//购物车中商品购买数累加值


    //购物车中SKU库存低于多少时，提示库存不足
    const SKU_STOCK_MIN_NUM = 5;



    /**
     * @param $uid
     * @param $skuId
     * @param $appSource
     * @param $releatWith
     *
     * 获取指定SKU的购物车信息
     *
     * @return mixed
     */
    public static function getInfoBySkuIdFromMaster($uid, $skuId, $appSource, $releatWith = false)
    {

        $info = self::select_master("*", Medoo::raw(' where uid=:uid and sku_id=:sku_id and app_source=:app_source for update', [':uid' => $uid, ':sku_id' => $skuId, ':app_source' => $appSource]));

        $info = array_shift($info);


        if (empty($info)) {
            return false;
        }

        self::formatInfo($info);


        if ($releatWith) {
            $skuInfo = mGoodsSku::getInfo($skuId);

            $info['sku_info'] = $skuInfo;
        }

        return $info;
    }


    public static function getCartWikiIdList($uid, $skuIds)
    {
        $list = self::select(['goods_id', 'sku_id'], ['uid' => $uid, 'sku_id' => $skuIds]);

        if (empty($list)) {
            return [];
        }

        $skuIdList = array_column($list, 'goods_id', 'sku_id');

        $goodsIdList = array_unique(array_values($skuIdList));

        if (!empty($goodsIdList)) {
            $goodsList = mGoodsBasicInfo::getInfoList($goodsIdList, ['wiki_id', 'goods_id']);

            $wikiList = array_column($goodsList, 'wiki_id', 'goods_id');

            return array_filter(array_map(function ($v) use ($wikiList) {

                $v = isset($wikiList[$v]) ? $wikiList[$v] : 0;

                return $v;
            }, $skuIdList), function ($val) {
                return ($val !== 0);
            });
        }
    }


    /**
     * 获取购物车中有效商品的总数
     */
    public static function getActiveSkuTotalBuyNum($uid, $appSource)
    {
        $count = self::count(['uid' => $uid, 'app_source' => $appSource,'status' => self::STATUS_ACTIVE]);

        return $count;
    }

    /**
     * 删除购物车中的SKU
     */
    public static function delSku($uid, $skuIds, $isForce = false)
    {
        if (!$isForce) {
            $data = self::update([
                'sell_price' => 0,
                'buy_price' => 0,
                'addtime' => '0000-00-00 00:00:00',
                'edittime' => '0000-00-00 00:00:00',
                'buy_num' => 0,
                'status' => self::STATUS_DELETE,
            ], ['uid' => $uid, 'sku_id' => $skuIds]);

        } else {

            self::delete(['uid' => $uid, 'sku_id' => $skuIds]);

        }


        return true;
    }

    public static function formatInfo(&$info)
    {
        if (empty($info)) {
            return;
        }


        foreach ($info as $key => &$value) {
            switch ($key) {
                case 'sku_attr':
                    $skuAttr = explode(',', $value);
                    $info['sku_attr_t1'] = isset($skuAttr[0]) ? $skuAttr[0] : 0;
                    $info['sku_attr_t2'] = isset($skuAttr[1]) ? $skuAttr[1] : 0;
                    break;
                case 'addtime':
                    $info['addtime_stamp'] = strtotime($value);
                    break;
            }
        }
    }

	public static function admGetAllNums(array $sku_ids)
	{
		return array_sum(
			self::select( "buy_num", [
				'sku_id' => $sku_ids
			] )
		);

	}

	public static function admMemberNumsByGoodsIds($goodsIds)
	{
		$infos = self::select('*', [
			'goods_id' => $goodsIds,
			'status' => self::STATUS_ACTIVE
		]);
		$goodsIdsGrpUid = [];
		foreach ($infos as $info) {
			if (!isset($goodsIdsGrpUid[$info['goods_id']]) || !in_array($info['goods_id'], $goodsIdsGrpUid[$info['goods_id']])) {
				$goodsIdsGrpUid[$info['goods_id']][]=$info['uid'];
			}
		}
		$results = [];
		foreach ($goodsIdsGrpUid as $goodsId => $uids) {
			$results[$goodsId] = count(array_unique($uids));
		}
		return $results;
	}

    /**
     * 根据goods_id信息获取加购总数
     * @param $goodsIds
     * @return array
     */
	public static function admGetCartNumByGoodsIds($goodsIds)
    {

        $result = self::select(['goods_id', 'count' => Medoo::raw("count('buy_num')")], [
            'AND' => [
                'goods_id' => $goodsIds,
            ],
            'GROUP' => ['goods_id']
        ]);

        return $result ? : [];
    }

    /**
     * 根据sku_id信息获取加购总数
     * @param $skuIds
     * @return array
     */
    public static function admGetCartNumBySkuIds($skuIds)
    {
        $result = self::select(['sku_id', 'count' => Medoo::raw("count('buy_num')")], [
            'AND' => [
                'sku_id' => $skuIds,
            ],
            'GROUP' => ['sku_id']
        ]);
        return $result ? : [];
    }

    /**
     * 根据sku_id信息获取加购人数
     * @param $skuIds
     * @return array
     */
    public static function admGetAddCartPeopleNumBySkuIds($skuIds)
    {
        $result = self::select(['sku_id', 'count' => Medoo::raw("count(DISTINCT `uid`)")], [
            'AND' => [
                'sku_id' => $skuIds,
            ],
            'GROUP' => ['sku_id', 'uid']
        ]);
        return $result;
    }

    /**
     * @desc 获取购物车中热门数据
     * @param string $startTime 起始时间
     * @param string $endTime 截止时间
     * @param array $testShopIds 测试店铺id集合
     * @return array
     */
    public static function getHotRankGoodsId($startTime, $endTime, array $testShopIds = [])
    {
        $fields = 'goods_id';
        $where = [
            "addtime[>]" => $startTime,
            "addtime[<]" => $endTime,
            "GROUP" => "goods_id",
        ];
        if ($testShopIds) {
            $where['shop_id[!]'] = $testShopIds;
        }
        return self::select($fields, $where);
    }

    /**
     * @desc 获取购物车中热门数据
     * @param string $startTime 起始时间
     * @param string $endTime 截止时间
     * @param int $limit 记录数量
     * @param array $testShopIds 测试店铺id集合
     * @param array $goodsIds 商品id集合
     * @return array
     */
    public static function getHotRank($startTime, $endTime, $limit = 10, array $testShopIds = [], array $goodsIds = [])
    {
        $fields = [
            'goods_id',
            'count' => Medoo::raw('COUNT(*)')
        ];
        $where = [
            "addtime[>]" => $startTime,
            "addtime[<]" => $endTime,
            "GROUP" => "goods_id",
            "ORDER" => ["count" => "DESC" ,"goods_id" => "DESC"],
            "LIMIT" => $limit,
        ];
        if ($testShopIds) {
            $where['shop_id[!]'] = $testShopIds;
        }
        if ($goodsIds) {
            $where['goods_id'] = $goodsIds;
        }
        return self::select($fields, $where);
    }

    /**
     * @desc 获取用户购物车中商品id集合
     * @param int $uid 用户id
     * @return array
     */
    public static function getGoodsIdsByUid($uid)
    {
        $fields = [
            'goods_id'
        ];
        $where = [
            "uid" => $uid,
        ];
        return self::select($fields, $where);
    }
}